using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using ExaminationSys.DataAccess.Entity;
using SQLinq;
using SQLinq.Dapper;

namespace ExaminationSys.DataAccess.Repository
{
    public class TeacherPrivilegeRelRepository : Repository<TeacherPrivilegeRel>
    {
        public TeacherPrivilegeRelRepository(SqlConnection context)
            : base(context)
        {
            db = context;
        }

        private SqlConnection db;

        public override TeacherPrivilegeRel GetById(dynamic id)
        {
            return base.ObjectSet.Get<TeacherPrivilegeRel>(db, id, null, null);
        }
    }
    public class TeacherPrivilegeRelService
    {
        private TeacherPrivilegeRelService()
        {
        }

        public List<TeacherPrivilegeRel> GetTeacherPrivilegeRelList(Guid teacherId)
        {
            using (var db = DataContent.DBServer())
            {
                var result = db.Query(from p in new SQLinq<TeacherPrivilegeRel>()
                                      where p.TeacherID == teacherId
                                      select p).ToList();
                return result;

            }
        }


        public bool TryAddTeacherPrivilegeRel(string teacherId, List<TeacherPrivilegeRel> teacherPrivilegeRels)
        {

            bool flag;

            using (var db = DataContent.DBServer())
            {
                var trans = db.BeginTransaction();
                try
                {
                    db.Execute(string.Format("delete  from TeacherPrivilegeRel where  TeacherID='{0}'", teacherId),null,trans);

                    foreach (var item in teacherPrivilegeRels)
                    {
                        int retCode = db.Execute(
                            @"insert into  TeacherPrivilegeRel(TeacherID,SectionID) values (@TeacherID,@SectionID)",
                            new[] {new {TeacherID = item.TeacherID, SectionID = item.SectionID}},trans);
                        if (retCode <= 0)
                        {
                            throw new Exception("error");
                        }
                    }
                    flag = true;
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    flag = false;
                }
            }
            return flag;
        }
    }
}